﻿package net.wangit.view.unit.component;

import java.util.HashMap;

import net.wangit.Row;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.framework.session.AgileSession;
import net.wangit.framework.util.DataProcessor;
import net.wangit.view.element.AutoLabelElement;
import net.wangit.view.element.ElementComponent;
import net.wangit.view.unit.UnitComponent;
import net.wangit.view.unit.UnitWriter;
import net.wangit.view.unit.grid.Group;
import net.wangit.view.unit.util.UnitShowModeUtil;


public class FormUnit extends UnitComponent {

	public FormUnit() {
	}

	protected void configure(Row row1) {
	}

	protected void cloneAfter(ActionContext ac) {
		super.cloneAfter(ac);
		initShowMode(ac);
		setRowsCss(new HashMap());
		attributes = new HashMap();
		if (rowsConfig != null)
			rowsConfig.reset();
		DataProcessor.loadData(ac, this);
	}

	public void addElement2Group(ActionContext ac, Group group,
			ElementComponent ec) {
		if (ec.isAddLabel() && ec.getTdColSpan() > 0)
			group.addElement(new AutoLabelElement(ec.getName()));
		group.addElement(ec);
	}

	public UnitWriter getWriter() {
		return new FormUnitWriter();
	}

	public boolean isOperable() {
		return !"s".equals(getShowMode());
	}

	protected void initShowMode(ActionContext ac) {
		String sessionKey = UnitShowModeUtil.getModeKey(this);
		AgileSession session = ActionContextHelper.getSession(ac);
		net.wangit.MapList snapshot = session.getSnapshot(this);
		if (snapshot != null) {
			setShowMode((String) ac.getSessionAttribute(sessionKey));
			return;
		}
		String requestKey = (new StringBuilder(String.valueOf(getId())))
				.append(".m").toString();
		String showMode = ac.getRequestParameter(requestKey);
		if (isValidShowMode(showMode)) {
			this.showMode = getValidShowMode(showMode);
			ac.setSessionAttribute(sessionKey, this.showMode);
			return;
		}
		showMode = ac.getRequestParameter("m");
		if (isValidShowMode(showMode)) {
			this.showMode = getValidShowMode(showMode);
			ac.setSessionAttribute(sessionKey, this.showMode);
			return;
		}
		showMode = (String) ac.getSessionAttribute(sessionKey);
		if (isValidShowMode(showMode)) {
			this.showMode = getValidShowMode(showMode);
			return;
		} else {
			this.showMode = "s";
			ac.setSessionAttribute(sessionKey, "s");
			return;
		}
	}

	protected boolean isValidShowMode(String showMode) {
		return "s".equals(showMode) || "e".equals(showMode)
				|| "a".equals(showMode);
	}

	private String getValidShowMode(String showMode) {
		if (!isAddable() && "a".equals(showMode) || !isEditable()
				&& "e".equals(showMode))
			return "s";
		else
			return showMode;
	}
}
